const http = require('http');
const socketIo = require('socket.io');

// 创建HTTP服务器
const server = http.createServer();

// 创建Socket.IO服务器
const io = socketIo(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

// 存储连接的客户端和会话数据
const clients = new Map();
const conversationData = new Map();

console.log('Socket.IO Chat服务器启动在 http://localhost:8080');

io.on('connection', (socket) => {
  console.log('新客户端连接:', socket.id);
  
  // 存储客户端信息
  clients.set(socket.id, {
    socket: socket,
    connectedAt: new Date(),
    conversations: new Set()
  });
  
  // 发送连接响应
  socket.emit('connect_response', {
    clientId: socket.id,
    serverTime: new Date().toISOString(),
    message: '连接成功建立'
  });
  
  // 处理用户消息
  socket.on('user_message', (data) => {
    try {
      console.log('收到用户消息:', data);
      const { conversationId, message, messageId } = data;
      
      if (!conversationId || !message) {
        socket.emit('error', {
          type: 'invalid_message',
          message: '消息格式无效'
        });
        return;
      }
      
      // 记录对话关联
      const clientInfo = clients.get(socket.id);
      if (clientInfo) {
        clientInfo.conversations.add(conversationId);
      }
      
      // 模拟处理用户消息
      processUserMessage(socket, conversationId, message, messageId);
      
    } catch (error) {
      console.error('处理用户消息失败:', error);
      socket.emit('error', {
        type: 'message_processing_error',
        message: '消息处理失败: ' + error.message
      });
    }
  });
  
  // 处理审核响应
  socket.on('audit_response', (data) => {
    try {
      console.log('收到审核响应:', data);
      const { conversationId, messageId, action } = data;
      
      if (!conversationId || !messageId || !action) {
        socket.emit('error', {
          type: 'invalid_audit_response',
          message: '审核响应格式无效'
        });
        return;
      }
      
      // 处理审核结果
      handleAuditResponse(socket, conversationId, messageId, action);
      
    } catch (error) {
      console.error('处理审核响应失败:', error);
      socket.emit('error', {
        type: 'audit_processing_error',
        message: '审核处理失败: ' + error.message
      });
    }
  });
  
  // 处理连接断开
  socket.on('disconnect', (reason) => {
    console.log('客户端断开连接:', socket.id, '原因:', reason);
    
    // 清理客户端数据
    const clientInfo = clients.get(socket.id);
    if (clientInfo) {
      // 清理相关对话数据
      clientInfo.conversations.forEach(conversationId => {
        const convData = conversationData.get(conversationId);
        if (convData && convData.clientId === socket.id) {
          conversationData.delete(conversationId);
        }
      });
    }
    
    clients.delete(socket.id);
  });
  
  // 处理错误
  socket.on('error', (error) => {
    console.error('Socket错误:', socket.id, error);
  });
});

// 处理用户消息
function processUserMessage(socket, conversationId, message, messageId) {
  // 存储对话数据
  if (!conversationData.has(conversationId)) {
    conversationData.set(conversationId, {
      clientId: socket.id,
      messages: [],
      tableData: [],
      createdAt: new Date()
    });
  }
  
  const convData = conversationData.get(conversationId);
  convData.messages.push({
    id: messageId,
    content: message,
    type: 'user',
    timestamp: new Date()
  });
  
  // 分析消息内容决定处理方式
  const analysis = analyzeMessage(message);
  
  if (analysis.requiresMatching) {
    // 开始匹配过程
    startMatchingProcess(socket, conversationId, message, analysis);
  } else if (analysis.requiresAudit) {
    // 需要审核
    requestAudit(socket, conversationId, message, analysis);
  } else {
    // 普通响应
    sendNormalResponse(socket, conversationId, message, analysis);
  }
}

// 开始匹配过程
function startMatchingProcess(socket, conversationId, message, analysis) {
  console.log('开始匹配过程:', conversationId);
  
  // 发送匹配开始通知
  socket.emit('match_update', {
    conversationId: conversationId,
    content: '开始匹配处理...',
    progress: 0,
    timestamp: new Date().toISOString()
  });
  
  // 模拟匹配过程
  let progress = 0;
  const matchingInterval = setInterval(() => {
    progress += Math.random() * 20 + 10;
    
    if (progress < 100) {
      socket.emit('match_update', {
        conversationId: conversationId,
        content: `匹配进度: ${Math.round(progress)}%`,
        progress: Math.round(progress),
        timestamp: new Date().toISOString()
      });
    } else {
      clearInterval(matchingInterval);
      
      // 匹配完成
      const tableData = generateTableData(conversationId, analysis);
      
      socket.emit('match_complete', {
        conversationId: conversationId,
        content: '匹配完成！找到 ' + tableData.length + ' 条相关数据',
        tableData: tableData,
        timestamp: new Date().toISOString()
      });
      
      // 存储表格数据
      const convData = conversationData.get(conversationId);
      if (convData) {
        convData.tableData.push(...tableData);
      }
    }
  }, 500 + Math.random() * 1000);
}

// 请求审核
function requestAudit(socket, conversationId, message, analysis) {
  console.log('请求审核:', conversationId);
  
  const auditMessageId = `audit_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  
  socket.emit('audit_request', {
    conversationId: conversationId,
    messageId: auditMessageId,
    content: `检测到敏感内容需要审核: "${message.substring(0, 50)}${message.length > 50 ? '...' : ''}"`
      + '\n\n请选择处理方式:',
    originalMessage: message,
    riskLevel: analysis.riskLevel || 'medium',
    timestamp: new Date().toISOString()
  });
}

// 发送普通响应
function sendNormalResponse(socket, conversationId, message, analysis) {
  console.log('发送普通响应:', conversationId);
  
  // 模拟处理延迟
  setTimeout(() => {
    const responses = generateNormalResponses(message, analysis);
    
    responses.forEach((response, index) => {
      setTimeout(() => {
        socket.emit('match_update', {
          conversationId: conversationId,
          content: response,
          timestamp: new Date().toISOString()
        });
      }, index * 1000);
    });
    
    // 可能生成一些表格数据
    if (Math.random() > 0.5) {
      setTimeout(() => {
        const tableData = generateTableData(conversationId, analysis, 3);
        
        socket.emit('match_complete', {
          conversationId: conversationId,
          content: '已为您生成相关数据',
          tableData: tableData,
          timestamp: new Date().toISOString()
        });
        
        // 存储表格数据
        const convData = conversationData.get(conversationId);
        if (convData) {
          convData.tableData.push(...tableData);
        }
      }, responses.length * 1000 + 500);
    }
  }, 300 + Math.random() * 700);
}

// 处理审核响应
function handleAuditResponse(socket, conversationId, messageId, action) {
  console.log('处理审核响应:', conversationId, messageId, action);
  
  const status = action === 'approve' ? 'approved' : 'rejected';
  const content = action === 'approve' 
    ? '审核通过，继续处理您的请求...'
    : '审核未通过，请修改您的请求内容';
  
  // 发送审核更新
  socket.emit('audit_update', {
    conversationId: conversationId,
    messageId: messageId,
    status: status,
    content: content,
    timestamp: new Date().toISOString()
  });
  
  // 如果审核通过，继续处理
  if (action === 'approve') {
    setTimeout(() => {
      const tableData = generateTableData(conversationId, { type: 'approved' });
      
      socket.emit('audit_update', {
        conversationId: conversationId,
        messageId: messageId,
        status: 'completed',
        content: '处理完成，已生成相关数据',
        tableData: tableData,
        timestamp: new Date().toISOString()
      });
      
      // 存储表格数据
      const convData = conversationData.get(conversationId);
      if (convData) {
        convData.tableData.push(...tableData);
      }
    }, 1500);
  }
}

// 分析消息内容
function analyzeMessage(message) {
  const lowerMessage = message.toLowerCase();
  
  // 检查是否需要匹配
  const matchingKeywords = ['匹配', '搜索', '查找', '检索', '分析', '统计'];
  const requiresMatching = matchingKeywords.some(keyword => lowerMessage.includes(keyword));
  
  // 检查是否需要审核
  const auditKeywords = ['敏感', '违规', '审核', '风险', '危险'];
  const requiresAudit = auditKeywords.some(keyword => lowerMessage.includes(keyword));
  
  // 确定风险等级
  let riskLevel = 'low';
  if (lowerMessage.includes('高风险') || lowerMessage.includes('危险')) {
    riskLevel = 'high';
  } else if (lowerMessage.includes('中风险') || lowerMessage.includes('敏感')) {
    riskLevel = 'medium';
  }
  
  return {
    requiresMatching,
    requiresAudit,
    riskLevel,
    messageLength: message.length,
    hasNumbers: /\d/.test(message),
    hasSpecialChars: /[!@#$%^&*(),.?":{}|<>]/.test(message)
  };
}

// 生成普通响应
function generateNormalResponses(message, analysis) {
  const responses = [
    '收到您的消息，正在处理...',
    '分析中，请稍候...',
  ];
  
  if (analysis.hasNumbers) {
    responses.push('检测到数字信息，正在进行数据分析...');
  }
  
  if (message.length > 50) {
    responses.push('您的消息内容较长，正在详细分析...');
  }
  
  responses.push('处理完成！');
  
  return responses;
}

// 生成表格数据
function generateTableData(conversationId, analysis, count = 5) {
  const categories = ['数据分析', '用户行为', '系统监控', '业务指标', '性能统计'];
  const statuses = ['成功', '处理中', '等待', '完成', '正常'];
  
  const tableData = [];
  
  for (let i = 0; i < count; i++) {
    tableData.push({
      id: `data_${Date.now()}_${i}_${Math.random().toString(36).substr(2, 6)}`,
      name: `数据项 ${i + 1}`,
      value: Math.floor(Math.random() * 10000) + 100,
      category: categories[Math.floor(Math.random() * categories.length)],
      status: statuses[Math.floor(Math.random() * statuses.length)],
      date: new Date().toISOString().split('T')[0],
      conversationId: conversationId
    });
  }
  
  return tableData;
}

// 服务器错误处理
server.on('error', (error) => {
  console.error('服务器错误:', error);
});

// 启动服务器
server.listen(8080, () => {
  console.log('Socket.IO Chat服务器正在监听端口 8080');
});

// 优雅关闭
process.on('SIGINT', () => {
  console.log('\n收到 SIGINT 信号，正在关闭服务器...');
  
  // 通知所有客户端服务器即将关闭
  io.emit('server_shutdown', {
    message: '服务器即将关闭，请保存您的工作',
    timestamp: new Date().toISOString()
  });
  
  // 等待一段时间让客户端处理
  setTimeout(() => {
    server.close(() => {
      console.log('服务器已关闭');
      process.exit(0);
    });
  }, 1000);
});

process.on('SIGTERM', () => {
  console.log('收到 SIGTERM 信号，正在关闭服务器...');
  server.close(() => {
    console.log('服务器已关闭');
    process.exit(0);
  });
});

// 定期清理过期数据
setInterval(() => {
  const now = new Date();
  const expireTime = 24 * 60 * 60 * 1000; // 24小时
  
  for (const [conversationId, data] of conversationData.entries()) {
    if (now - data.createdAt > expireTime) {
      conversationData.delete(conversationId);
      console.log('清理过期对话数据:', conversationId);
    }
  }
}, 60 * 60 * 1000); // 每小时清理一次